#include "form.h"
#include "ui_form.h"

Form::Form(QWidget *parent,QTcpSocket *tcpsock) :
    QWidget(parent),
    ui(new Ui::Form),tcpsock(tcpsock)
{
    ui->setupUi(this);
    connect(tcpsock, SIGNAL(readyRead()), this, SLOT(read()));
    connect(tcpsock, SIGNAL(disconnected()), this, SLOT(disconnected()));
}

Form::~Form()
{
    if (tcpsock) {
            disconnect(tcpsock, nullptr, this, nullptr);  // 断开与socket的所有连接
            tcpsock->close();
        }
    delete ui;
}

void Form::read(){
    QString newData = tcpsock->readAll();
    QString allData = "客户端："  + newData;
    ui->plainTextEdit->appendPlainText(allData);
}

void Form::disconnected()
{
    emit clientDisconnected(this);
}



void Form::on_pushButton_clicked()
{
    tcpsock->write(ui->textEdit->toPlainText().toUtf8());
    QString allData = "我："  + ui->textEdit->toPlainText().toUtf8();
    ui->plainTextEdit->appendPlainText(allData);
    ui->textEdit->setPlainText("");
}
